﻿package Cain.camera
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.ActivityEvent;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.media.Camera;
	import flash.media.Video;
	import Cain.mc_cesh.Cesher;
	import flash.text.TextField;
	/**
	 * 視訊框
	 * 找不到攝影機 "nocamera"
	 * 開始取得畫面 ActivityEvent.ACTIVITY
	 * @author Cain
	 */
	public class WebCanForm extends Sprite 
	{
		private const cain:String = "As3 code by 雄獅旅遊 in 2010 cainmaila@gmail.com";
		private var camera:Camera;//攝影機
		private var video:Video;//畫面
		/**
		 * 偵錯模式
		 */
		public var debug:Boolean = false;
		/**
		 * 初始化
		 * @param	_ww 寬
		 * @param	_hh 高
		 */
		private var ww:Number;
		private var hh:Number;
		public function WebCanForm(_ww:Number,_hh:Number)
		{
			ww = _ww;
			hh = _hh;
			setup();
			init();
		}
		
		private function setup():void
		{
			
		}
		
		private function init():void
		{
			addEventListener(Event.ADDED_TO_STAGE, addthis);
		}
		
		private function addthis(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, addthis);
			var tf:TextField = new TextField();
			tf.text = cain;
			tf.visible = false;
			addChild(tf);
			get_web_can();//取得視訊
		}
		
		private function get_web_can():void
		{
			camera = Camera.getCamera();
			 if (camera != null) {
				
                camera.addEventListener(ActivityEvent.ACTIVITY, activityHandler);//取得影相後
                video = new Video(ww, hh);
                video.attachCamera(camera);
                addChild(video);
				
            } else {
				
				dispatchEvent(new Event("nocamera"));
            }
		}
		
		private function activityHandler(e:ActivityEvent):void //取得影相後
		{
			dispatchEvent(e);
		}
		/**
		 * 咖圖
		 * @return 影像資料
		 */
		public function get_bitmap():BitmapData
		{
			var cesher:Cesher = new Cesher(this, new Rectangle(0, 0, ww, hh));
			
			if (debug) 
			{
				cesher.shoit();
			}
			return cesher.bitmapData();
		}
	}
	
}